import 'package:flutter/material.dart';
import 'package:flutter_trip/TabsPage/CityListPage.dart';
import 'package:flutter_trip/Widget/SearchBarWidget.dart';
import 'package:geolocator/geolocator.dart';

class NavBarWidget extends StatefulWidget {
  /// 导航栏透明度
  final double alpha;
  NavBarWidget({@required this.alpha});

  @override
  _NavBarWidgetState createState() => _NavBarWidgetState();
}

class _NavBarWidgetState extends State<NavBarWidget> {
  /// 城市名
  String _city = '北京市';

  @override
  void initState() {
    super.initState();

    _getUserLocation();
  }

  @override
  Widget build(BuildContext context) {
    double topMargin = MediaQuery.of(context).padding.top;
    return Column(
      children: <Widget>[
        Container(
            color: Color.fromARGB((255 * widget.alpha).toInt(), 255, 255, 255),
            padding: EdgeInsets.only(top: topMargin),
            child: Stack(
              children: <Widget>[
                SearchBarWidget(
                    isHomeSearchBar: true,
                    isActive: widget.alpha >= 0.5,
                    city: _city,
                    tapHomeSearchBar: () =>
                        Navigator.of(context).pushNamed('/search'),
                    cityButtonClick: () async {
                      String cityName = await Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (context) => CityListPage(_city)));
                      if (cityName != null) {
                        setState(() {
                          _city = cityName;
                        });
                      }
                    },
                    microphoneButtonClick: () =>
                        Navigator.of(context).pushNamed('/speakSearch'))
              ],
            )),
        Container(
          height: widget.alpha >= 1.0 ? 1.0 : 0.0,
          decoration: BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 0.5)]),
        )
      ],
    );
  }

  void _getUserLocation() async {
    try {
      Geolocator geolocator = Geolocator();
      Position position = await geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.high);
      List<Placemark> list = await geolocator.placemarkFromPosition(position);
      Placemark placemark = list.first;
      setState(() {
        _city = placemark.locality;
      });
    } catch (error, stack) {
      print('没有定位权限 请配置权限');
    }
  }
}
